package controller

import (
	"a-common/myerr"
	"a-system/domain/pojo"
	"a-system/service"
	"fmt"
	"sync"

	"github.com/gofiber/fiber/v2"
)

var (
	sysOperlogControllerTemp *SysOperlogController
	sysOperlogService        = service.NewSysOperlogService()
	sysOperlogControllerOnce sync.Once
)

type SysOperlogController struct{}

func NewSysOperlogController() *SysOperlogController {
	sysOperlogControllerOnce.Do(func() {
		sysOperlogControllerTemp = &SysOperlogController{}
	})
	return sysOperlogControllerTemp
}

// List 列表
func (m *SysOperlogController) List(c *fiber.Ctx) error {
	var args pojo.SysOperlogDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	err := args.Validator()
	if err != nil {
		return err
	}

	vPage, err := sysOperlogService.List(&args)
	if err != nil {
		return err
	}
	return Resp(c, vPage)
}

// Export 导出
func (m *SysOperlogController) Export(c *fiber.Ctx) error {
	var args pojo.SysOperlogDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}

	f, err := sysOperlogService.Export(&args)
	if err != nil {
		return err
	}

	c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, "操作日志表.xlsx"))
	err = f.Write(c.Response().BodyWriter())
	if err != nil {
		return err
	}
	return nil
}

// Clear 清空
func (m *SysOperlogController) Clear(c *fiber.Ctx) error {
	err := sysOperlogService.Clear()
	if err != nil {
		return err
	}
	return Ok(c)
}
